package en.kaist.cs408.acav;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import en.kaist.cs408.R;


//classe qui instancie une conversation pour un patient
public class Conversation extends Activity implements OnItemLongClickListener {
	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
 
	//La "view" liste qui affiche toutes les conversations du patient
	private ListView mlvTextMatches;
	//l'adapter associ� au view avec l'utilisation d'un ArrayList<String>
	private MyAdapter mlistAdapt;
	//bouton pour parler
	private Button mbtSpeak;
	//alert dialog qui affiche la confirmation de suppression d'une ligne de la conversation
	private AlertDialog alertDialog;
	//variable qui r�cup�re la position de la ligne s�lectionn�e sur l'event OnLongClickItem
	private int mPosition;
	
	//la variable qui r�cup�re le nom du patient
	public String nomDuPatient;
	//l'instance de la base de donn�es
	static BaseDeDonnees 	db;
	//l'instance SQLiteDatabase
	SQLiteDatabase 		dataBase;
	

	/**
	 * Instancie les �l�ments "view" de l'application
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		checkVoiceRecognition();
		
		setContentView(R.layout.conversation);
		
        db = new BaseDeDonnees(this);
        db.open();
        
        nomDuPatient = getIntent().getStringExtra("nomPatient");

		TextView textViewToChange = (TextView) findViewById(R.id.nomDuPatient);
		textViewToChange.setText(nomDuPatient + "\n-----------------------------");
		
		mlistAdapt = new MyAdapter(new ArrayList<Student>(), this);
		remplirConversationsHistorique();
		
		mlvTextMatches = (ListView) findViewById(R.id.listview);
		

		mlvTextMatches.setOnItemLongClickListener(new OnItemLongClickListener() {

					public boolean onItemLongClick(
							AdapterView<?> arg0, View arg1,
							int position, long arg3) {

						mPosition = position;
						initAlertDialog();
						return false;
					}

				});
		mlvTextMatches.setAdapter(mlistAdapt);
		
		mbtSpeak = (Button) findViewById(R.id.buttonspeaker);
	}
	
	
	/**
	*Initialise le pop-up qui va s'afficher pour la confirmation de la suppression d'une ligne
	*/
	private void initAlertDialog() {
		alertDialog = new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Supprimer ?")
				.setNegativeButton("Non",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								mPosition = -1;
							}
						})
				.setPositiveButton("Oui",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								//db.supprimerUnePhrase(nomDuPatient, mlistAdapt.getItem(mPosition));
								mlistAdapt.remove(mlistAdapt.getItem(mPosition));
								mlistAdapt.notifyDataSetChanged();
								mPosition = -1;
								
							}
						}).create();
		alertDialog.show();
	}
 
 
	/**
	*D�tecte si la fonctionnalit� "voice recognizer" est pr�sente sur le mobile android
	*/
	public void checkVoiceRecognition() {

		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() == 0) {
			mbtSpeak.setEnabled(false);
			mbtSpeak.setText("Voice recognizer not present");
			Toast.makeText(this, "Voice recognizer not present", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	/**
	*Utilise la fonctionnalit� "voice recognizer" du mobile android
	*/
	public void speak(View view) {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
	 
		intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
	 
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
	 
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}
	
	
	/**
	*Remplit l'adapter avec la liste des phrases d'un patient pr�sentes dans la base de donn�es
	*/
	public void remplirConversationsHistorique(){
		
		ArrayList<String> listeTempo = db.getListePhrases(nomDuPatient);
		
		for(int i = 0; i < listeTempo.size(); i++){

			//mlistAdapt.add(listeTempo.get(i));
		}
	}
	
	
	/**
	*L'�v�nement lanc� lorsque l'on appuie sur le bouton "Cliquez ici" afin de pouvoir
	*enregistrer une nouvelle ligne de conversation
	*/
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)

			//Si "Voice recognition" est OK alors retourne "RESULT_OK"
			if (resultCode == RESULT_OK) {

				//r�cup�re tous les r�sultats de voice recognition
				ArrayList<String> textMatch = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				if (!textMatch.isEmpty()) {
					//r�cup�re le r�sultat le plus pr�cis de voice recognition
					Calendar c = Calendar.getInstance();
		    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		    		String formattedDate = df.format(c.getTime());
					
		    		db.insererDonnees_t_conversation(nomDuPatient, formattedDate, textMatch.get(0));
			        // associe l'adapter � la vue
					//mlistAdapt.add(textMatch.get(0));
					mlvTextMatches.setAdapter(mlistAdapt);
					
				}
				// Result code pour les diff�rentes erreurs.
			} else if (resultCode == RecognizerIntent.RESULT_AUDIO_ERROR) {
				showToastMessage("Audio Error");
			} else if (resultCode == RecognizerIntent.RESULT_CLIENT_ERROR) {
				showToastMessage("Client Error");
			} else if (resultCode == RecognizerIntent.RESULT_NETWORK_ERROR) {
				showToastMessage("Network Error");
			} else if (resultCode == RecognizerIntent.RESULT_NO_MATCH) {
				showToastMessage("No Match");
			} else if (resultCode == RecognizerIntent.RESULT_SERVER_ERROR) {
				showToastMessage("Server Error");
			}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	*Le pop-up affich�e lors de l'appui long
	*/
	void showToastMessage(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	//L'�v�nement associ� au clic sur les boutons
	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
			int position, long arg3) {
		return false;
	}

}
